<template>
  <div class="accounts-management">
    <div class="page-header">
      <h1>账户管理</h1>
      <p class="subtitle">银行账户与资金账户管理</p>
    </div>

    <!-- 账户统计和操作区域 -->
    <div class="stats-actions-section">
      <div class="accounts-stats">
        <div class="stat-item">
          <h3>账户总数</h3>
          <p class="amount">{{ accounts.length }}</p>
        </div>
        <div class="stat-item">
          <h3>总余额</h3>
          <p class="amount positive">¥{{ formatNumber(totalBalance) }}</p>
        </div>
        <div class="stat-item">
          <h3>活跃账户</h3>
          <p class="amount">{{ activeAccountsCount }}</p>
        </div>
      </div>

      <div class="actions-bar">
        <button class="btn btn-primary" @click="showAddModal = true">
          <span class="btn-icon">+</span>
          新增账户
        </button>
        <div class="search-box">
          <input
            v-model="searchKeyword"
            placeholder="搜索账户编号或名称..."
            @input="filterAccounts"
            class="search-input"
          >
        </div>
      </div>
    </div>

    <!-- 账户列表 -->
    <div class="table-section">
      <div class="table-container">
        <table class="accounts-table">
          <thead>
            <tr>
              <th>账户编号</th>
              <th>账户名称</th>
              <th>账户类型</th>
              <th>余额</th>
              <th>状态</th>
              <th>创建时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="account in filteredAccounts" :key="account.id">
              <td>{{ account.accountNumber }}</td>
              <td>{{ account.accountName }}</td>
              <td>{{ account.accountType }}</td>
              <td class="amount" :class="account.balance >= 0 ? 'positive' : 'negative'">
                ¥{{ formatNumber(account.balance) }}
              </td>
              <td>
                <span class="status" :class="account.status === 1 ? 'active' : 'inactive'">
                  {{ account.status === 1 ? '启用' : '停用' }}
                </span>
              </td>
              <td>{{ formatDateTime(account.createTime) }}</td>
              <td>
                <button class="btn btn-small btn-primary" @click="viewAccount(account)">查看</button>
                <button class="btn btn-small btn-secondary" @click="editAccount(account)">编辑</button>
                <button class="btn btn-small btn-danger" @click="deleteAccount(account.id)">删除</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 新增/编辑账户模态框 -->
    <div v-if="showAddModal || showEditModal" class="modal-overlay" @click="closeModal">
      <div class="modal" @click.stop>
        <div class="modal-header">
          <h3>{{ showEditModal ? '编辑账户' : '新增账户' }}</h3>
          <button class="close-btn" @click="closeModal">×</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveAccount">
            <div class="form-group">
              <label>账户编号 *</label>
              <input
                v-model="accountForm.accountNumber"
                type="text"
                required
                :disabled="showEditModal"
              >
            </div>
            <div class="form-group">
              <label>账户名称 *</label>
              <input v-model="accountForm.accountName" type="text" required>
            </div>
            <div class="form-group">
              <label>账户类型</label>
              <select v-model="accountForm.accountType">
                <option value="基本存款账户">基本存款账户</option>
                <option value="一般存款账户">一般存款账户</option>
                <option value="专用存款账户">专用存款账户</option>
                <option value="临时存款账户">临时存款账户</option>
                <option value="现金账户">现金账户</option>
              </select>
            </div>
            <div class="form-group">
              <label>账户余额</label>
              <input v-model="accountForm.balance" type="number" step="0.01">
            </div>
            <div class="form-group">
              <label>状态</label>
              <select v-model="accountForm.status">
                <option :value="1">启用</option>
                <option :value="0">停用</option>
              </select>
            </div>
            <div class="form-actions">
              <button type="button" class="btn btn-secondary" @click="closeModal">取消</button>
              <button type="submit" class="btn btn-primary">{{ showEditModal ? '更新' : '保存' }}</button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 账户详情模态框 -->
    <div v-if="showDetailModal" class="modal-overlay" @click="showDetailModal = false">
      <div class="modal" @click.stop>
        <div class="modal-header">
          <h3>账户详情</h3>
          <button class="close-btn" @click="showDetailModal = false">×</button>
        </div>
        <div class="modal-body">
          <div class="detail-item">
            <label>账户编号:</label>
            <span>{{ selectedAccount.accountNumber }}</span>
          </div>
          <div class="detail-item">
            <label>账户名称:</label>
            <span>{{ selectedAccount.accountName }}</span>
          </div>
          <div class="detail-item">
            <label>账户类型:</label>
            <span>{{ selectedAccount.accountType }}</span>
          </div>
          <div class="detail-item">
            <label>账户余额:</label>
            <span class="amount" :class="selectedAccount.balance >= 0 ? 'positive' : 'negative'">
              ¥{{ formatNumber(selectedAccount.balance) }}
            </span>
          </div>
          <div class="detail-item">
            <label>状态:</label>
            <span class="status" :class="selectedAccount.status === 1 ? 'active' : 'inactive'">
              {{ selectedAccount.status === 1 ? '启用' : '停用' }}
            </span>
          </div>
          <div class="detail-item">
            <label>创建时间:</label>
            <span>{{ formatDateTime(selectedAccount.createTime) }}</span>
          </div>
          <div class="detail-item">
            <label>更新时间:</label>
            <span>{{ formatDateTime(selectedAccount.updateTime) }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { apiGet, apiPost, apiPut, apiDelete } from '../../utils/api.js'

// 响应式数据
const accounts = ref([])
const filteredAccounts = ref([])
const searchKeyword = ref('')
const showAddModal = ref(false)
const showEditModal = ref(false)
const showDetailModal = ref(false)
const selectedAccount = ref({})
const editingAccountId = ref(null)

// 表单数据
const accountForm = ref({
  accountNumber: '',
  accountName: '',
  accountType: '基本存款账户',
  balance: 0,
  status: 1
})

// 计算属性
const totalBalance = computed(() => {
  return accounts.value.reduce((sum, account) => sum + Number(account.balance || 0), 0)
})

const activeAccountsCount = computed(() => {
  return accounts.value.filter(account => account.status === 1).length
})

// 过滤账户
const filterAccounts = () => {
  if (!searchKeyword.value.trim()) {
    filteredAccounts.value = accounts.value
  } else {
    const keyword = searchKeyword.value.toLowerCase()
    filteredAccounts.value = accounts.value.filter(account =>
      account.accountNumber?.toLowerCase().includes(keyword) ||
      account.accountName?.toLowerCase().includes(keyword)
    )
  }
}

// 监听搜索关键词变化
watch(searchKeyword, filterAccounts)

// 格式化数字
const formatNumber = (num) => {
  if (!num) return '0.00'
  return new Intl.NumberFormat('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  }).format(num)
}

// 格式化日期时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return ''
  return new Date(dateStr).toLocaleString('zh-CN')
}

const loadAccounts = async () => {
  try {
    const data = await apiGet('/finance/accounts')

    if (data.content) {
      accounts.value = data.content
    } else {
      accounts.value = data
    }
    // 初始化过滤后的账户列表
    filteredAccounts.value = accounts.value
  } catch (error) {
    console.error('加载账户数据时出错:', error)
    accounts.value = []
  }
}

const saveAccount = async () => {
  try {
    let result
    if (showEditModal.value) {
      result = await apiPut(`/finance/accounts/${editingAccountId.value}`, accountForm.value)
    } else {
      result = await apiPost('/finance/accounts', accountForm.value)
    }

    if (result.code === 0) {
      alert(result.message || '保存成功')
      showAddModal.value = false
      showEditModal.value = false
      await loadAccounts()
    } else {
      alert(result.message || '保存失败')
    }
  } catch (error) {
    console.error('保存账户时出错:', error)
    alert('保存失败')
  }
}

const deleteAccount = async (id) => {
  if (!confirm('确定要删除这个账户吗？')) return

  try {
    const result = await apiDelete(`/finance/accounts/${id}`)

    if (result.code === 0) {
      alert(result.message || '删除成功')
      await loadAccounts()
    } else {
      alert(result.message || '删除失败')
    }
  } catch (error) {
    console.error('删除账户时出错:', error)
    alert('删除失败')
  }
}

// 查看账户详情
const viewAccount = (account) => {
  selectedAccount.value = account
  showDetailModal.value = true
}

// 编辑账户
const editAccount = (account) => {
  editingAccountId.value = account.id
  accountForm.value = { ...account }
  showEditModal.value = true
}

// 关闭模态框
const closeModal = () => {
  showAddModal.value = false
  showEditModal.value = false
  showDetailModal.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  accountForm.value = {
    accountNumber: '',
    accountName: '',
    accountType: '基本存款账户',
    balance: 0,
    status: 1
  }
  editingAccountId.value = null
}

onMounted(() => {
  loadAccounts()
})
</script>

<style scoped>
.accounts-management {
  padding: 20px;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  position: relative;
}

.accounts-management::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="25" cy="25" r="1" fill="rgba(255,255,255,0.1)"/><circle cx="75" cy="75" r="1" fill="rgba(255,255,255,0.1)"/><circle cx="50" cy="10" r="0.5" fill="rgba(255,255,255,0.1)"/><circle cx="10" cy="60" r="0.5" fill="rgba(255,255,255,0.1)"/><circle cx="90" cy="40" r="0.5" fill="rgba(255,255,255,0.1)"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>');
  opacity: 0.3;
  pointer-events: none;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 25px 30px;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.3);
  position: relative;
  overflow: hidden;
}

.page-header::before {
  content: '';
  position: absolute;
  top: -50%;
  right: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
  animation: float 6s ease-in-out infinite;
}

@keyframes float {
  0%, 100% { transform: translateY(0px) rotate(0deg); }
  50% { transform: translateY(-20px) rotate(180deg); }
}

.page-header h1 {
  font-size: 32px;
  color: white;
  margin-bottom: 8px;
  font-weight: 700;
  text-shadow: 0 2px 4px rgba(0,0,0,0.3);
  position: relative;
  z-index: 1;
}

.subtitle {
  color: rgba(255, 255, 255, 0.9);
  font-size: 16px;
  position: relative;
  z-index: 1;
}

.stats-actions-section {
  background: rgba(255, 255, 255, 0.95);
  padding: 25px 30px;
  border-radius: 16px;
  margin-bottom: 25px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
  position: relative;
  overflow: hidden;
}

.stats-actions-section::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: linear-gradient(90deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
}

.accounts-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 24px;
  margin-bottom: 24px;
}

.stat-item {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  text-align: center;
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.stat-item h3 {
  margin: 0 0 12px 0;
  color: #495057;
  font-size: 1rem;
}

.stat-item .amount {
  font-size: 1.8rem;
  font-weight: bold;
  color: #2c3e50;
  margin: 0;
}

.amount.positive {
  color: #28a745;
}

.amount.negative {
  color: #dc3545;
}

.actions-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 12px;
  font-weight: 600;
  transition: all 0.3s ease;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  display: flex;
  align-items: center;
}

.btn-primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
  color: white !important;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4) !important;
}

.btn-primary:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
}

.btn-primary:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.btn-secondary {
  background: linear-gradient(135deg, #6c757d 0%, #495057 100%) !important;
  color: white !important;
  box-shadow: 0 4px 15px rgba(108, 117, 125, 0.4) !important;
}

.btn-secondary:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(108, 117, 125, 0.6);
}

.btn-danger {
  background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%) !important;
  color: white !important;
  box-shadow: 0 4px 15px rgba(231, 76, 60, 0.4) !important;
}

.btn-danger:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(231, 76, 60, 0.6);
}

.btn-small {
  padding: 4px 8px;
  font-size: 10px;
}

.btn-icon {
  margin-right: 8px;
  font-weight: bold;
  font-size: 16px;
}

.search-box input {
  padding: 12px 16px;
  border: 2px solid #e1e5e9;
  border-radius: 12px;
  font-size: 14px;
  min-width: 250px;
  background: rgba(255, 255, 255, 0.9);
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.search-box input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1);
  transform: translateY(-2px);
}

.search-box input:hover {
  border-color: #adb5bd;
  transform: translateY(-1px);
}

.table-section {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
  position: relative;
  overflow: hidden;
  margin-bottom: 25px;
}

.table-section::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: linear-gradient(90deg, #4facfe 0%, #00f2fe 50%, #43e97b 100%);
}

.table-container {
  overflow-x: auto;
  padding: 20px 20px 0 20px;
  background: transparent;
  border-radius: 0;
  box-shadow: none;
  border: none;
  backdrop-filter: none;
  position: static;
  overflow: visible;
}

.accounts-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

.accounts-table th,
.accounts-table td {
  padding: 12px 8px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.accounts-table th {
  background: #f8f9fa;
  font-weight: 600;
  color: #495057;
  padding: 16px 12px;
  border: none;
  position: relative;
  border-bottom: 2px solid #e9ecef;
}

.accounts-table tbody tr {
  transition: all 0.3s ease;
  border-bottom: 1px solid rgba(225, 229, 233, 0.5);
}

.accounts-table tr:hover {
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

.accounts-table tbody tr:last-child {
  border-bottom: none;
}

.status {
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
  display: inline-block;
}

.status.active {
  background: rgba(40, 167, 69, 0.1);
  color: #28a745;
  border: 1px solid rgba(40, 167, 69, 0.3);
}

.status.inactive {
  background: rgba(220, 53, 69, 0.1);
  color: #dc3545;
  border: 1px solid rgba(220, 53, 69, 0.3);
}

.action-btn.delete {
  background: #dc3545;
}

.action-btn.delete:hover {
  background: #c82333;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 12px;
  width: 90%;
  max-width: 600px;
  max-height: 80vh;
  overflow: hidden;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  border: 1px solid #e1e5e9;
  position: relative;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 18px 20px 16px 20px;
  border-bottom: 1px solid #e1e5e9;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
  color: white !important;
  border-radius: 12px 12px 0 0;
}

.modal-header h3 {
  margin: 0;
  color: white;
  font-size: 16px;
  font-weight: 600;
}

.close-btn {
  background: rgba(255, 255, 255, 0.2) !important;
  border: none !important;
  font-size: 16px !important;
  cursor: pointer !important;
  color: white !important;
  width: 24px !important;
  height: 24px !important;
  border-radius: 50% !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  transition: all 0.2s !important;
}

.close-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: scale(1.1);
}

.modal-body {
  padding: 16px 20px;
  max-height: calc(80vh - 120px);
  overflow-y: auto;
  overflow-x: hidden;
  width: 100%;
  box-sizing: border-box;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  color: #2c3e50;
  font-weight: 600;
  font-size: 12px;
}

.form-group input,
.form-group select {
  width: 100% !important;
  padding: 8px 12px !important;
  border: 2px solid #e1e5e9 !important;
  border-radius: 6px !important;
  font-size: 12px !important;
  transition: all 0.3s ease !important;
  background: #ffffff !important;
  box-sizing: border-box !important;
}

.form-group input:focus,
.form-group select:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
  transform: translateY(-1px);
}

.form-group input:hover,
.form-group select:hover {
  border-color: #adb5bd;
}

.form-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 24px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #e9ecef;
}

.detail-item:last-child {
  border-bottom: none;
}

.detail-item label {
  font-weight: 500;
  color: #495057;
}

.detail-item span {
  color: #6c757d;
}

@media (max-width: 768px) {
  .accounts-management {
    padding: 16px;
  }

  .accounts-stats {
    grid-template-columns: 1fr;
  }

  .actions-bar {
    flex-direction: column;
    align-items: stretch;
  }

  .search-box input {
    min-width: auto;
  }

  .stats-actions-section {
    padding: 20px;
  }

  .table-section {
    margin: 0 10px 25px 10px;
  }

  .accounts-table {
    font-size: 0.8rem;
  }

  .accounts-table th,
  .accounts-table td {
    padding: 8px;
  }

  .detail-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
}
</style>

